<template>
  <div class="body_box">
    <div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="书名">
          <el-input v-model="formInline.bookName" style="width: 180px" placeholder="输入书名" clearable />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="formInline.author" style="width: 180px" placeholder="输入作者" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-cascader @change="clearCascader" :options="options" v-model="selectedValue" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="onClear">清空</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="showDialog">新增书籍</el-button>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%">
        <!-- <el-table-column prop="" label="序号" width="180" /> -->
        <!-- 封面图列：使用作用域插槽渲染图片 -->
        <el-table-column label="封面图" width="200">
          <template #default="scope">
            <img :src="scope.row.book_url" alt="封面图" style="width: 100px; height: 150px">
          </template>
        </el-table-column>

        <!-- 其他列保持原有写法 -->
        <el-table-column prop="book_name" label="书名" width="150" />
        <el-table-column prop="book_author" label="作者" width="150" />
        <el-table-column prop="category_name" label="类型" width="180" />
        <el-table-column  label="评论数" width="150">
          <template #default="scope">
            <div style="height: 150px;line-height:150px;" @click="handleSeleBookDetail(scope.row.book_id)">{{ scope.row.comment_number }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="subscribe_number" label="订阅数" width="150" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row.book_id)" style="margin-right: 10px;">
              修改
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.book_name,scope.row.book_id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="searchData.current" :page-size="searchData.limit" :total="total" :pager-count="6"
        style="text-align: center;margin-top: 20px;" layout=" prev, pager, next, total,jumper"
        @current-change="getData" />
    </div>
    <div>
      <book-dialog v-model:visible="dialogVisible" :book-id="editBookId" :options="options" @save="handleSave" />
      <comment-dialog v-model:commentDialog="commentDialog" :book-id="commentBookId"/>
    </div>
  </div>
</template>
<script setup>

import { ref, reactive, onMounted } from 'vue'
import api from "../../api/api"
import CommentDialog from './CommentDialog.vue'
import BookDialog from './BookDialog.vue'
import { ElMessageBox } from 'element-plus'
const formInline = reactive({
  bookName: '',
  author: '',
  type: '',
})
const rawData = ref([])
const selectedValue = ref([]);
const options = ref([])
function transformToCascader(data) {
  const parentMap = new Map() // 用于存放已处理的父级

  return data.reduce((acc, item) => {
    // 处理父级
    if (!parentMap.has(item.parent_value)) {
      const parent = {
        value: item.parent_value,
        label: item.parent_label,
        children: []
      }
      acc.push(parent)
      parentMap.set(item.parent_value, parent)
    }
    // 处理子级
    const parent = parentMap.get(item.parent_value)
    parent.children.push({
      value: item.child_value,
      label: item.child_label
    })

    return acc
  }, [])
}
const commentDialog = ref(false)
const commentBookId = ref('') 
// BookList.vue 中打开弹窗的方法
function handleSeleBookDetail(book_id) {

    // 后设置弹窗状态
    commentBookId.value = book_id
    commentDialog.value = true
}
function getAllCategory() {
  api.post('/getAllCategory')
    .then(response => {
      rawData.value = response.data
      options.value = transformToCascader(rawData.value)
    })
    .catch(error => {
      console.error('请求失败:', error);
    });
}
function clearCascader(value) {
  if (value == null) {
    selectedValue.value = []
  }
}
function onSubmit() {
  formInline.type = selectedValue.value[1]
  // console.log("点击查询", formInline)
  searchData.current = 1
  getData()
}
function onClear() {
  formInline.bookName = ""
  formInline.author = ""
  formInline.type = ""
  selectedValue.value = [];
}
// tableData-表格数据列表，total-数据总长度
const tableData = ref([])
const total = ref(0)
// searchData-向后端分页查询的对象，即当前页和每页总数
const searchData = reactive({
  current: 1,
  limit: 5
})
function tableAddData() {
  // 合并查询条件到总数请求
  const params = {
    ...formInline,
    type: selectedValue.value.length > 0
      ? selectedValue.value[selectedValue.value.length - 1]
      : ''
  }

  api.post('/getBooksNumber', params)
    .then(response => {
      total.value = response.data
    })
    .catch(error => {
      console.error('请求失败:', error)
    })
}
//传入分页参数
function pageQuery() {
  // 合并分页参数和查询条件
  const params = {
    ...searchData,
    ...formInline
  }
  api.post('/AdminBookList', params)
    .then(response => {
      console.log('返回数据:', response.data)
      tableData.value = response.data
    })
    .catch(error => {
      console.error('请求失败:', error)
    })
}
function getData(val = 1) {
  searchData.current = val
  pageQuery()
  tableAddData()
}
const dialogVisible = ref(false)

const editBookId = ref('')  // 新增用于存储要编辑的书名

// 显示弹窗
const showDialog = (bookId = '') => {
  editBookId.value = bookId
  dialogVisible.value = true
}

function handleEdit(bookId) {
  console.log('修改的书名:', bookId);
  showDialog(bookId)
}

function handleDelete(bookName,bookId) {
  ElMessageBox.confirm(
    `确定要删除《${bookName}》吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      console.log('确认删除:', bookName)
      // 这里可以添加实际的删除逻辑
      api.post('/deleteBookDetail', { bookId: bookId })
        .then(response => {
          console.log(response.data)
        })
        .catch(error => {
          console.error('请求失败:', error)
        })
      // getData()
      onSubmit()
    })
    .catch(() => {
      console.log('取消删除')
    })
}
const handleSave = (formData) => {
  console.log('保存的数据：', formData)
  // alert(editBookName.value)
  if (editBookId.value != "[object PointerEvent]") {
    // 修改图书
    console.log('修改图书:', formData)
    api.post('/updateBookDetail', formData)
      .then(response => {
        console.log(response.data)
        onSubmit()
      })
      .catch(error => {
        console.error('请求失败:', error)
      })

  } else {
    // 新增图书
    console.log('新增图书:', formData)
    api.post('/insertBookDetail', formData)
      .then(response => {
        console.log(response.data)
        onSubmit()
      })
      .catch(error => {
        console.error('请求失败:', error)
      })
  }
  // onSubmit()
  // getData()
  dialogVisible.value = false
}
onMounted(async () => {
  tableAddData()
  getAllCategory()
  getData()
})
</script>
<style>
.body_box {
  margin-left: 50px;
}
</style>
